package com.example.service;

import com.gitee.zhuhjay.xunfei.sdk.AppClient;
import com.gitee.zhuhjay.xunfei.sdk.AppClientFactory;
import com.gitee.zhuhjay.xunfei.sdk.model.ApiAuth;
import com.gitee.zhuhjay.xunfei.sdk.model.ApiResponse;
import com.gitee.zhuhjay.xunfei.sdk.model.Text;
import okhttp3.WebSocketListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
public class XhStreamClientServiceImpl extends WebSocketListener implements XhStreamClientService, InitializingBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${xfxh.appId}")
    private String appId;

    @Value("${xfxh.apiKey}")
    private String apiKey;

    @Value("${xfxh.apiSecret}")
    private String apiSecret;

    private AppClientFactory appClientFactory;

    @Override
    public void afterPropertiesSet() throws Exception {
        ApiAuth apiAuth = ApiAuth.builder()
                .appId(appId)
                .apiKey(apiKey)
                .apiSecret(apiSecret).build();
        this.appClientFactory = AppClientFactory.create(apiAuth, 1, 1, 2);
    }

    @Override
    public AppClientFactory getAppClientFactory() {
        return this.appClientFactory;
    }

    @Override
    public AppClient getClientV1() {
        return this.appClientFactory.openClientV1();
    }

    @Override
    public AppClient getClientV2() {
        return this.appClientFactory.openClientV2();
    }

    @Override
    public AppClient getClientV3() {
        return this.appClientFactory.openClientV3();
    }

    @Override
    public ApiResponse send(String text, Text... history) throws Exception {
        Future<ApiResponse> apiResponseFuture = this.getClientV3().sendAsync(text, history);
        return apiResponseFuture.get();
    }

    @Override
    public ApiResponse send(String text) throws Exception {
        Future<ApiResponse> apiResponseFuture = this.getClientV3().sendAsync(text);
        return apiResponseFuture.get();
    }
}
